/*
 * Copyright 2009 Gary Brown
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *
 * Change History:
 * 7 Mar 2009 : Initial version created by gary
 */
package org.betonthemove.ui.android;

import org.betonthemove.platform.*;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
//import android.net.Uri;
import android.os.Bundle;
//import android.view.Menu;
//import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

public class MarketView extends Activity implements OnClickListener,
						Runnable {

	private static final int MARKET_UPDATE_INTERVAL = 10000;
	public static final String MARKET_ID_ATTR = "org.betonthemove.MarketID";
	public static final String MARKET_NAME_ATTR = "org.betonthemove.MarketName";
	public static final String MARKET_START_DATE_ATTR = "org.betonthemove.MarketStartDate";
	public static final String MARKET_CATEGORY_ATTR = "org.betonthemove.MarketCategory";
	public static final String MARKET_DUE_IN_PLAY_ATTR = "org.betonthemove.MarketDueInPlay";

	private static final int WAITING_DIALOG = 1;
    private static final int ERROR_DIALOG = 2;
    private static final int ERROR_MESSAGE_DISPLAY_DELAY = 4000;

    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		m_marketId=getIntent().getIntExtra(MARKET_ID_ATTR, -1);
		m_eventTypeId=getIntent().getIntExtra(EventTypeSelection.EVENT_TYPE_ID_ATTR, -1);
		String marketName=getIntent().getStringExtra(MARKET_NAME_ATTR);
		m_dueInPlay=getIntent().getBooleanExtra(MARKET_DUE_IN_PLAY_ATTR, false);
		long startDate=getIntent().getLongExtra(MARKET_START_DATE_ATTR, -1);
		String marketCategory=getIntent().getStringExtra(MARKET_CATEGORY_ATTR);
		
		setContentView(R.layout.marketview);
		
		m_marketIdField=(TextView)findViewById(R.id.marketid); 
		
		String marketText=marketName;
		
		if (marketCategory != null) {
			marketText = marketCategory+": "+marketText;
		}
		
		m_marketIdField.setText(marketText);
		m_marketIdField.setTextColor(0xff111111);
		m_marketIdField.setTextSize(14);
		
		String datetime="";
		
		if (startDate > (System.currentTimeMillis()-(24*60*60*1000))) {
			datetime = new java.util.Date(startDate).toString();
		}
		
		m_marketTimeField=(TextView)findViewById(R.id.markettime); 		
		m_marketTimeField.setText(datetime);
		m_marketTimeField.setTextColor(0xff111111);
		m_marketTimeField.setTextSize(10);
		
		if (m_dueInPlay) {
			m_marketIdField.setBackgroundResource(R.color.solid_yellow);
			m_marketTimeField.setBackgroundResource(R.color.solid_yellow);
		}
    }
		
	protected void onStart() {
		super.onStart();

		f_end = false;
		
        runOnUiThread(this);   
	}
	
	@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case WAITING_DIALOG: {
                ProgressDialog dialog = new ProgressDialog(this);
                dialog.setMessage("Retrieving market entrants...");
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                return dialog;
            }
            case ERROR_DIALOG: {
                ProgressDialog dialog = new ProgressDialog(this);
                dialog.setMessage("ERROR: "+m_error);
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                return dialog;
            }
        }
        return null;
    }

    public void run() {
    	
    	// Check if should just end
    	if (f_end) {
    		return;
    	}
    	
    	if (m_state == 0) {
    		showDialog(WAITING_DIALOG);
    		
    		m_state++;
    		
    		new Thread(this).start();
    	} else if (m_state == 1) {

    		BettingPlatform platform=BettingPlatformFactory.getBettingPlatform();
        
	        try {
		        m_marketDetails = platform.getMarketDetails(m_marketId, false);
		        
	    		m_currency = DisplayHelper.getCurrencySymbol(
    					platform.getCurrency());
		        
		        m_state++;
	        } catch(Exception e) {
	        	m_error = e.getLocalizedMessage();
	        	
	        	m_state = 5;
	        }
	        
	        runOnUiThread(this);

    	} else if (m_state == 2) {
    		
    		if (m_dueInPlay) {
    			if (m_marketDetails.getBetDelay() > 0) {
    				m_marketIdField.setBackgroundResource(R.color.solid_green);
					m_marketTimeField.setBackgroundResource(R.color.solid_green);
    			} else {
    				m_marketIdField.setBackgroundResource(R.color.solid_yellow);
    				m_marketTimeField.setBackgroundResource(R.color.solid_yellow);
    			}
    		}
    		
    		TableLayout tl=(TableLayout)findViewById(R.id.marketview); 
    		
    		for (int i=0; i < m_marketDetails.getEntrants().size(); i++) {
    			MarketEntrant entrant=m_marketDetails.getEntrants().get(i);
    			
    			TableRow row=new TableRow(this);
    			row.setPadding(1, 1, 1, 1);
    			
    			TextView text=new TextView(this);
    			text.setText(entrant.getName());
    			text.setTextColor(0xff111111);
    			text.setWidth(160);
    			text.setTag(entrant.getSelectionId());
    			
    			row.addView(text);
    			
    			MarketData md=new MarketData(m_marketId,
    					entrant.getSelectionId(),
    					entrant.getName(), true,
						entrant.getCurrentBackOdds(),
						entrant.getCurrentBackPrice());
    			
    			Button button1=new Button(this);
    			button1.setText(buttonText(md));
    			button1.setWidth(80);
    			button1.setPadding(2, 0, 0, 0);
    			button1.setBackgroundDrawable(getResources().getDrawable(R.drawable.back));
    			button1.setTag(md);
    			
    			button1.setOnClickListener(this);
    			
    			row.addView(button1);
    			
    			md = new MarketData(m_marketId,
    					entrant.getSelectionId(), 
    					entrant.getName(), false,
						entrant.getCurrentLayOdds(),
						entrant.getCurrentLayPrice());
    			
    			Button button2=new Button(this);
    			button2.setText(buttonText(md));
    			button2.setWidth(80);
    			button2.setPadding(2, 0, 0, 0);
    			button2.setBackgroundDrawable(getResources().getDrawable(R.drawable.lay));
    			button2.setTag(md);
    				
    			button2.setOnClickListener(this);

    			row.addView(button2);
    			
    			tl.addView(row);
    		}
    		
    		m_state++;

    		dismissDialog(WAITING_DIALOG);
	        
	        new Thread(this).start();
	        
    	} else if (m_state == 3) {
    		
    		BettingPlatform platform=BettingPlatformFactory.getBettingPlatform();
            
	        try {
	        	synchronized(this) {
	        		wait(MARKET_UPDATE_INTERVAL);
	        	}
	        	
		        m_marketDetails = platform.getMarketDetails(m_marketId, true);
		        
		        m_state++;
		        
	        } catch(Exception e) {
	        	m_error = e.getLocalizedMessage();
	        	
	        	m_state = 5;
	        }
	        
	        runOnUiThread(this);

    	} else if (m_state == 4) {
    		if (m_dueInPlay) {
    			if (m_marketDetails.getBetDelay() > 0) {
    				m_marketIdField.setBackgroundResource(R.color.solid_green);
					m_marketTimeField.setBackgroundResource(R.color.solid_green);
    			} else {
    				m_marketIdField.setBackgroundResource(R.color.solid_yellow);
    				m_marketTimeField.setBackgroundResource(R.color.solid_yellow);
    			}
    		}
    		
	        TableLayout tl=(TableLayout)findViewById(R.id.marketview); 
    		
	        if (tl.getChildCount() == m_marketDetails.getEntrants().size()) {
	    		for (int i=0; i < tl.getChildCount(); i++) {
	    			TableRow row=(TableRow)tl.getChildAt(i);
	    			MarketEntrant entrant=m_marketDetails.getEntrants().get(i);
	    			
	    			TextView tv=(TextView)row.getChildAt(0);
	    			int selectionId=(Integer)tv.getTag();
	    			
	    			if (selectionId == entrant.getSelectionId()) { 			
		    			Button button1=(Button)row.getChildAt(1);
		
		    			MarketData md=(MarketData)button1.getTag();
		    					    			
		    			md.setPrice(entrant.getCurrentBackOdds());
		    			md.setStake(entrant.getCurrentBackPrice());
		    			
		    			button1.setText(buttonText(md));
		    			
		    			Button button2=(Button)row.getChildAt(2);
		    			
		    			md = (MarketData)button2.getTag();
		    			
		    			md.setPrice(entrant.getCurrentLayOdds());
		    			md.setStake(entrant.getCurrentLayPrice());

		    			button2.setText(buttonText(md));
	    			} else {
	    				// TODO: Handle mismatch selection ids
	    			}
	    		}
	        }
    		
    		m_state = 3;
    		
    		new Thread(this).start();
	        
    	} else if (m_state == 5) {

    		dismissDialog(WAITING_DIALOG);
	        
	        showDialog(ERROR_DIALOG);
	        
	        m_state++;
	        
	        new Thread(this).start();
	        
    	} else if (m_state == 6) {

    		try {
    			synchronized(this) {
    				wait(ERROR_MESSAGE_DISPLAY_DELAY);
    			}
    		} catch(Exception e) {
    			e.printStackTrace();
    		}
    		
    		m_state++;
    		
    		runOnUiThread(this);
    		
    	} else if (m_state == 7) {
    		
    		dismissDialog(ERROR_DIALOG);
    		
    		m_error = null;
    		
    		if (m_marketDetails == null) {
    			finish();
    		} else {
    			// Go back to refresh state
    			m_state = 3;
    			
    	        new Thread(this).start();
    		}
    	}
    }

    protected String buttonText(MarketData md) {
    	String ret=null;
    	
    	double price=Math.round(md.getPrice()*100)/(double)100;
    	int stake=(int)md.getStake();
    	
    	if (price > 0.0) {
    		ret = ""+price+"\n"+m_currency+stake;
    	} else {
    		ret = "\n";
    	}

    	return(ret);
    }

	public void onClick(View arg0) {
		
        Intent intent = new Intent();
        intent.setClass(MarketView.this, PlaceBetView.class);
        
        intent.putExtra(PlaceBetView.MARKET_DATA_ATTR, (MarketData)arg0.getTag());
        
        startActivity(intent);
	}
	
	protected void onStop() {
		super.onStop();
		
		f_end = true;
	}
		
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);		
	}

	private TextView m_marketIdField=null;
	private TextView m_marketTimeField=null;
	private int m_state=0;
	private int m_marketId=0;
	private int m_eventTypeId=0;
	private boolean f_end=false;
	private boolean m_dueInPlay=false;
	private MarketDetails m_marketDetails=null;
	private String m_error=null;
	private String m_currency=null;
}
